package com.kira.solo.schedule.pojo

import androidx.compose.runtime.Immutable
import com.kira.solo.schedule.list.CaseListUiState
import kotlinx.serialization.Serializable
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale

/**
 *
 * @packageName com.kira.solo.schedule.pojo
 * @date 2024/1/25 10:05
 * @author zhanglei
 */
@Immutable
data class CaseEditUiState(
    val taskInfo: CasePeriodTaskInfo,
    val uiState: CaseListUiState,
) {
    companion object {
        val INIT = CaseEditUiState(CasePeriodTaskInfo.INIT, CaseListUiState.INIT)
    }
}

/**
 * 定时执行任务
 */
@Immutable
@Serializable
data class CasePeriodTaskInfo(
    val taskId: Long,
    val periodType: PeriodType,
    val time: Time,
    val caseIds: List<Long>,
) {
    companion object {
        val INIT = CasePeriodTaskInfo(-1L, PeriodType.Once, Time(8, 0), emptyList())
    }
}

/**
 * 构建时间
 */
@Serializable
data class CasePeriodTaskInfoGroup(val taskMap: Map<Long, CasePeriodTaskInfo>) {
    companion object {
        val INIT = CasePeriodTaskInfoGroup(emptyMap())
    }
}

val formatter = SimpleDateFormat("hh:mm a", Locale.CHINA)

/**
 * 时间
 */
@Serializable
@Immutable
data class Time(val hour: Int, val minute: Int) {
    val calendar by lazy {
        val cal = Calendar.getInstance()
        cal.set(Calendar.HOUR_OF_DAY, hour)
        cal.set(Calendar.MINUTE, minute)
        cal.isLenient = false
        cal
    }

    val display by lazy {
        formatter.format(calendar.time) ?: ""
    }
}

@Serializable
@Immutable
sealed interface PeriodType {
    val display: String

    /**
     * 仅一次
     */
    @Serializable
    @Immutable
    data object Once : PeriodType {
        override val display: String = "只触发一次"
    }

    /**
     * 每天
     */
    @Serializable
    @Immutable
    data object EveryDay : PeriodType {
        override val display: String = "每天触发"
    }

    /**
     * 周一至周五
     */
    @Serializable
    @Immutable
    data object WorkDay : PeriodType {
        override val display: String = "工作日（周一至周五）"
    }

    /**
     * 自定义，周一至周日
     */
    @Serializable
    @Immutable
    data class Custom(val days: List<Int> = emptyList()) : PeriodType {
        override val display: String = if (days.isEmpty()) "自定义" else days.fold("") { acc, i ->
            acc + i.toWeekDay + ","
        }
    }

    companion object {
        val allType = listOf(Once, EveryDay, WorkDay, Custom())
    }
}

private val Int.toWeekDay: String
    get() = when (this) {
        1 -> "周一"
        2 -> "周二"
        3 -> "周三"
        4 -> "周四"
        5 -> "周五"
        6 -> "周六"
        7 -> "周七"
        else -> throw IllegalArgumentException("not support $this")
    }
